package com.example.demo53.ui.Group;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;


import com.example.demo53.R;
import com.example.demo53.databinding.FragmentGroupBinding;


import com.example.demo53.methods.net.receive_message;
import com.example.demo53.ui.Group.menu.OpenGroup;
import com.example.demo53.ui.Temperation.double_color_temp;

import com.example.demo53.ui.Temperation.a_rpgLight;
import com.example.demo53.util.Adapter.GridViewAdapter;
import com.example.demo53.util.been.Light_item;

import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;



import static com.example.demo53.methods.net.receive_message.pw;

public class GroupFragment extends Fragment {

    private TextView test1;
    private TextView test2;
    private TextView test3;
    private TextView test4;
    private GridView mGridView;
    private GridView mGridView0;
    private EditText gv_edit;
    private GroupViewModel groupViewModel;
    private FragmentGroupBinding binding;

    private List<Integer> img_list=new ArrayList<>();;
    private List<String> tv_list=new ArrayList<>();;
    public static  ArrayList<Light_item> light_items = new ArrayList<>();
    private ArrayList<Light_item> light_items2 = new ArrayList<>();
    private GridViewAdapter adapter;
    private GridViewAdapter adapter0;
    private boolean optionMenuOn = false;  //标示是否要显示optionmenu
    private Menu aMenu;         //获取optionmenu
    public   int count =0;
    private Light_item a1;

    private ArrayList<Light_item> g_light_items;
    private ArrayList<ArrayList> group_lists= new ArrayList<>();
    private List<String> g_groupNames = new ArrayList<>();//新建灯泡组的名字集合

    //搞GridView的 点击刷新时更新gv1
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 1) {
                rebuild_Gridview(light_items,mGridView);

            }
        }
    };

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        setHasOptionsMenu(true);

        groupViewModel =
                new ViewModelProvider(this, new ViewModelProvider.NewInstanceFactory()).get(GroupViewModel.class);
        binding = FragmentGroupBinding.inflate(inflater, container, false);
        View root = binding.getRoot();
//        test3 = binding.test3;
//        test1 = binding.test1;
//        test2 = binding.test2;
//        test4=binding.test4;
        mGridView0 = binding.gv0;
        gv_edit = binding.gvEdit;
        mGridView = binding.gv1;
//        mGridView.setNumColumns(3);
//        initDatas();


        //rebuild_Gridview();




        setListener();


        return root;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }

        public  void  setListener() {


//            test1.setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    Intent intent = new Intent();
//                    intent.setClass(getActivity(), utiltest1.class);
//                    startActivity(intent);
//                }
//            });
//
//            test2.setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    Intent intent = new Intent();
//                    intent.setClass(getActivity(), double_color_temp.class);
//                    startActivity(intent);
//                }
//            });
//
//            test3.setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    Intent intent = new Intent();
//                    intent.setClass(getActivity(), uniLight.class);
//                    startActivity(intent);
//                }
//            });
//            test4.setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
////                    a1 = new Light_item("1","23",R.drawable.ic_withe_dlight);
////                    light_items.add(a1);
//                    receive_message b = new receive_message();
//                    b.start();
//
//                    Toast.makeText(getActivity(), "正在搜索灯具....", Toast.LENGTH_SHORT).show();
//
//                    new Timer().schedule(new TimerTask() {
//                        @Override
//                        public void run() {
//
//                           for(;count<light_items.size();count++){
////                               if(tv_list.contains(light_items.get(count-1).getId())){
////                                   light_items.remove(light_items.get(count-1));
////                                   --count;
////                                   continue;
////                               }
//                                Message msg = new Message();
//                                msg.what = 1;
//                                handler.sendMessage(msg);
//
//                                pw=false;
//                            }
//                        }
//                    }, 3 * 1000);
////--------------------两种挂起程序的方法--------------------
//////                        sleep(5000);
//////                        TimeUnit.SECONDS.sleep(5);
//                }
//            });
            //灯泡的点击事件
            mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view,
                                        int position, long id) {
                        Toast.makeText(getActivity(), "灯具", Toast.LENGTH_SHORT).show();


               if(adapter.getg_selectItem_state()==0){
                   adapter.setSeclection(position);
                   adapter.notifyDataSetChanged();
                    if(light_items.get(position).getKind().equals("1")){
                    Intent intent = new Intent();
                    intent.setClass(getActivity(), a_rpgLight.class);
                    startActivity(intent);
}

                    if(light_items.get(position).getKind().equals("2")){
                        Intent intent = new Intent();
                        intent.setClass(getActivity(), double_color_temp.class);
                        startActivity(intent);
                    }

                    if(light_items.get(position).getKind().equals("3")){
                        Intent intent = new Intent();
                        intent.setClass(getActivity(), a_rpgLight.class);
                        startActivity(intent);
                    }
}

               //新建组时对组的成员进行选择
               if(adapter.getg_selectItem_state()==1) {
                   //创建新的list来装选中的item。再用list装list
                   //-------------------现在只能靠位置定位，待改进-----------------------------
                   g_light_items.add(light_items.get(position));

                    }
                    //intent.putExtra("id",position);跨activity传送值的方法

//                    if (position != parent.getChildCount()-2 ){

//                    }
//                    switch (position){
//                        case 0:
//
//                    }
                }
            });


            //点击group的跳转
            mGridView0.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view,
                                        int position, long id) {

                    Intent intent = new Intent();
                    intent.setAction("action");
                    intent.putExtra("mlist",group_lists.get(position));
//                    Bundle bundle = new Bundle();
//                    bundle.putSerializable("mlist",group_lists.get(position));
//                    intent.putExtras(bundle);
                    startActivity(intent);
//                    Intent intent = new Intent();
//                    intent.setClass(getActivity(), OpenGroup.class);
//                                        intent.setAction("action");
//                    intent.putExtra("mlist",group_lists.get(position));
//                    startActivity(intent);
                }
            });
        }


    public void rebuild_Gridview(@NonNull ArrayList<Light_item> list, @NonNull GridView gridView){



            img_list.add(list.get(count - 1).getImg());
//        tv_list.add("123");//id注入
            tv_list.add(list.get(count - 1).getId());//id注入

        //或许修改adapter，直接传子项而不是数组会更好
        adapter = new GridViewAdapter(getActivity(), img_list, tv_list);
        gridView.setAdapter(adapter);
        //notifyDataSetChanged 可以在修改适配器绑定的数组后，不用重新刷新Activity，通知Activity更新ListView
        adapter.notifyDataSetChanged();
//        GridViewAdapter mAdapter=new GridViewAdapter(getActivity() ,  list  , tv_list);
//        mGridView.setAdapter(mAdapter);

    }

    public void rebuild_Gridview2(@NonNull ArrayList<ArrayList> list, GridView gridView){

         List<Integer> img_list0 = new ArrayList<>();
         List<String> tv_list0 = new ArrayList<>();
        int n = list.size();
        for(int c = 0;c<n;c++){
            img_list0.add(R.drawable.ic_withe_dlight);
            tv_list0.add(g_groupNames.get(c));
        }


        //或许修改adapter，直接传子项而不是数组会更好
        adapter0 = new GridViewAdapter(getActivity(), img_list0, tv_list0);
        gridView.setAdapter(adapter0);
        //notifyDataSetChanged 可以在修改适配器绑定的数组后，不用重新刷新Activity，通知Activity更新ListView
        adapter0.notifyDataSetChanged();

    }


//去重方法1，对class类的重复无效去重
//    public static ArrayList De_duplication(ArrayList<Light_item> a){
//        Set<Light_item> set = new HashSet<>();
//        ArrayList<Light_item> newList = new ArrayList<>();
//        for (Light_item cd : a) {
//            if (set.add(cd)) {
//                newList.add(cd);
//            }
//        }
//        return newList;
//    }
//方法2，遍历去重,用在线程receive——message了 （contains方法就是垃圾
//    private void dd(String a){
//        for (Light_item i :light_items){
//            if(i.getId()==a){
//                light_items.remove(i);
//            }
//        }
//
//    }

    /**
     *
     * @param menu
     * menu相关方法（下三项
     */

    //在这个方法里调用setIconVisible()
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        menu.clear();
        inflater.inflate(R.menu.group_menu, menu);
        setIconsVisible(menu,true);
        super.onCreateOptionsMenu(menu, inflater);
    }

    /**
     *这里是通过反射显示图片
     * 但图片间隔，大小都无法设置
     * 故暂不使用
     */
    //fragment中设置menu的icon可显示
    private void setIconsVisible(Menu menu, boolean flag) {
        //判断menu是否为空
        if (menu != null) {
            try {
                //如果不为空,就反射拿到menu的setOptionalIconsVisible方法
                Method method = menu.getClass().getDeclaredMethod("setOptionalIconsVisible", Boolean.TYPE);
                //暴力访问该方法
                method.setAccessible(true);
                //调用该方法显示icon
                method.invoke(menu, flag);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case R.id.gItem1:
                receive_message b = new receive_message();
                b.start();

                Toast.makeText(getActivity(), "正在搜索灯具....", Toast.LENGTH_SHORT).show();
//                return true;
            case R.id.gItem2:
                new Timer().schedule(new TimerTask() {
                    @Override
                    public void run() {

                        for(;count<light_items.size();count++){
//                               if(tv_list.contains(light_items.get(count-1).getId())){
//                                   light_items.remove(light_items.get(count-1));
//                                   --count;
//                                   continue;
//                               }
                            Message msg = new Message();
                            msg.what = 1;
                            handler.sendMessage(msg);

                            pw=false;
                        }
                    }
                }, 3 * 1000);
                return true;

            case R.id.gAddGroup:
                optionMenuOn = true;
                checkOptionMenu();
                //-------------------是否算是新创建的ArrayList------------------
                g_light_items = new ArrayList<>();
                if(adapter!=null) {
                    adapter.setg_selectItem_state(1);
                }
                return true;

            case R.id.gfalse:
                optionMenuOn = false;
                checkOptionMenu();
                if(adapter!=null) {
                    adapter.setg_selectItem_state(0);
                }
//                g_light_items.clear();
                return true;

            case R.id.gtrue:
                optionMenuOn = false;
                checkOptionMenu();
                g_groupNames.add(gv_edit.getText().toString());
                group_lists.add(g_light_items);
                rebuild_Gridview2(group_lists,mGridView0);

                if(adapter!=null) {
                    adapter.setg_selectItem_state(0);
                }


                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    //在加载menu前先加载此方法，先获取menu 方便设置menu的item的可见
    public void onPrepareOptionsMenu(Menu menu){
             aMenu = menu;
        checkOptionMenu();


    }

    private void checkOptionMenu() {
        if (null != aMenu) {
            if(optionMenuOn) {
                aMenu.getItem(2).setVisible(true);
                aMenu.getItem(3).setVisible(true);
                gv_edit.setVisibility(View.VISIBLE);
            }
            if(!optionMenuOn) {
                aMenu.getItem(2).setVisible(false);
                aMenu.getItem(3).setVisible(false);
                gv_edit.setVisibility(View.INVISIBLE);
            }
        }
    }


            /* 利用反射机制调用MenuBuilder的setOptionalIconsVisible方法设置mOptionalIconsVisible为true，给菜单设置图标时才可见
     * 让菜单同时显示图标和文字
     * ***************当然这是要在activity中用的，fragment要用另一个！！！！！！！！！！！！！！！！！！！！！！！！
     */
//    @Override
//    public boolean onMenuOpened(int featureId, Menu menu) {
//        if (menu != null) {
//            if (menu.getClass().getSimpleName().equalsIgnoreCase("MenuBuilder")) {
//                try {
//                    Method method = menu.getClass().getDeclaredMethod("setOptionalIconsVisible", Boolean.TYPE);
//                    method.setAccessible(true);
//                    method.invoke(menu, true);
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//            }
//        }
//        return super.onMenuOpened(featureId, menu);
//    }


}